package org.hnxxxy.ebms.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.*;
import org.hnxxxy.ebms.common.Result;
import org.hnxxxy.ebms.common.constant.OSSConstant;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @Author: wei
 * @Date: 2020/11/7 13:41
 */
@Component
public class OssUtil {


    @Value("${alicloud.oss.endpoint}")
    private static String endpoint;

    @Value("${alicloud.access-key}")
    private static String accessId;

    @Value("${alicloud.secret-key}")
    private static String secretKey;

    /**
     * OSS文件上传功能
     * @param multipartFile
     * @return
     */
    public Result upload(MultipartFile multipartFile){
        String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        System.out.println(format);
        String dir = format+"/"; // 用户上传文件时指定的前缀。
        OSS ossClient =  getOssClient();
        String backUrl = null;
        try {
            String newFileName = createFileName(multipartFile.getOriginalFilename());  // 建立文件名
            ossClient.putObject(OSSConstant.BUCKET, dir + newFileName, multipartFile.getInputStream()); // 上传图片
//            URL url = ossClient.generatePresignedUrl(OSSConstant.BUCKET,dir+newFileName,new Date(System.currentTimeMillis()+3600));
//            System.out.println(url.toString());
            backUrl = "http://" + OSSConstant.BUCKET + "." + endpoint + "/" + dir + newFileName; // 拼接图片路径
            
        } catch (Exception e) {
            //Assert.fail(e.getMessage());
            System.out.println(e.getMessage());
        } finally {
            ossClient.shutdown();
        }
        return Result.success(backUrl);
    }


    public String createFileName(String fileName){
        String sub = fileName.substring(fileName.lastIndexOf(".")); // 获取扩展名
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String newName = simpleDateFormat.format(new Date())+"-"+ UUID.randomUUID()+sub;
        return newName;
    }

    /**
     * 获取文件的信息
     * @param fileName 文件名
     */
    public Result getFileInfo(String fileName){
        OSS ossClient = getOssClient();
        Map<String,Object> result = new HashMap<>();
        // 获取文件的部分元信息
//        SimplifiedObjectMeta objectMeta = ossClient.getSimplifiedObjectMeta(OSSConstant.BUCKET,fileName);
//        result.put("size ",objectMeta.getSize());
//        result.put("ETag",objectMeta.getETag());
//        result.put("lastModified",objectMeta.getLastModified());

        // 获取全部的元信息
        ObjectMetadata metadata = ossClient.getObjectMetadata(OSSConstant.BUCKET,fileName);
        result.put("contentType",metadata.getContentType());
        SimpleDateFormat simpleDateFormat = null;
        try {
            simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            if (metadata.getExpirationTime() != null){
                result.put("expirationTime",simpleDateFormat.format(metadata.getExpirationTime()));
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        result.put("size",metadata.getContentLength());
        result.put("ETag",metadata.getETag());

        // 关闭OSSClient
        ossClient.shutdown();

        return Result.success(result);
    }

    /**
     * 文件下载
     * @param fileName 要下载的文件名
     * @param localFileName 下载到本地的文件名包括路径
     */
    public Result downloadFile(String fileName,String localFileName){
        OSS ossClient = getOssClient();

        ossClient.getObject(new GetObjectRequest(OSSConstant.BUCKET,fileName),new File(localFileName));

        ossClient.shutdown();

        return Result.success("下载文件成功");
    }

    private static OSS getOssClient(){
        return new OSSClientBuilder().build(endpoint,accessId,secretKey);
    }


    /**
     * 删除单个文件
     * @param fileName 删除的文件夹名或者文件名
     * @return
     */
//    public Result deleteFile(String fileName){
//        OSS ossClient = new OSSClientBuilder().build(endpoint,accessId,secretKey);
//
//        // 删除文件。如需删除文件夹，请将ObjectName设置为对应的文件夹名称。如果文件夹非空，则需要将文件夹下的所有object删除后才能删除该文件夹。
//        ossClient.deleteObject(OSSConstant.BUCKET, fileName);
//
//        ossClient.shutdown();
//
//        return new Result(true,StatusCode.OK,"删除文件成功");
//    }
//
//    public Result<List<String>> deleteFiles(List<String> fileNames){
//        OSS ossClient = new OSSClientBuilder().build(endpoint,accessId,secretKey);
//
//        DeleteObjectsResult deleteObjectsResult = ossClient.deleteObjects(new DeleteObjectsRequest(OSSConstant.BUCKET).withKeys(fileNames));
//        List<String> deletedObjects = deleteObjectsResult.getDeletedObjects();
//        System.out.println(deletedObjects);
//
//        return new Result<List<String>>(true,StatusCode.OK,"批量删除成功",deletedObjects);
//    }

}
